package robot

import (
	"context"
	"net/url"
	"regexp"
	"sale-admin/config/mysql"
	"sale-admin/internal/app/grpc/client"
	"sale-admin/internal/app/grpc/protoc/system_admin"
	"sale-admin/internal/models"
	"strings"

	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
	"github.com/PuerkitoBio/goquery"
)

type SalesStatement struct{}

// setGoods 设置补货

func HandlerGoodsDetail(str string) string {

	SystemAdminClient, clientErr := client.GetSystemAdminClient()
	if clientErr != nil {
		return ""
	}
	reader := strings.NewReader(str)
	doc, err := goquery.NewDocumentFromReader(reader)
	if err == nil {
		doc.Find("img").Each(func(_ int, s *goquery.Selection) {
			src, _ := s.Attr("src")
			URL, _ := url.Parse(src)
			match, matchErr := regexp.MatchString("^(/file/sale-admin/).*(/temp/).*$", URL.Path)
			if matchErr == nil && match {
				//文件确认
				var req system_admin.ConfirmFileReq
				req.FileUrl = URL.Path
				res, err1 := SystemAdminClient.ConfirmFile(context.Background(), &req)
				if err1 != nil && res.Code != 0 {
					logx.Error(context.Background(), "goods confirm file error", logx.Any("res", res), logx.Any("err", err.Error()))
					return
				}
				ImagePath := URL.Scheme + "://" + URL.Host + res.FileUrl
				s.SetAttr("src", ImagePath) //修改标签的内容
			}
		})
	}
	newGoods, _ := goquery.OuterHtml(doc.Selection)
	returnHtml := strings.TrimSuffix(strings.TrimPrefix(newGoods, "<html><head></head><body>"), "</body></html>")
	return returnHtml
}

// 新增重要提示
func (s SalesStatement) AddNotice(merchant_id, name, content string) (err error) {
	var data models.MaSalesStatement
	data.Title = name                          // 最多4个字符
	data.Content = HandlerGoodsDetail(content) // 编辑器
	rowsAffected := mysql.NewDB().Model(&models.MaSalesStatement{}).
		Create(&data).RowsAffected
	// 写入数据
	if rowsAffected > 0 {
		return nil
	}
	return err
}

// 编辑
func (s SalesStatement) EditNotice(merchant_id string, id int, name, content string) (err error) {
	var data models.MaSalesStatement
	data.Title = name                          // 最多4个字符
	data.Content = HandlerGoodsDetail(content) // 编辑器
	rowsAffected := mysql.NewDB().Model(&models.MaSalesStatement{}).Where("id = ?", id).
		Updates(&data).RowsAffected
	// 写入数据
	if rowsAffected > 0 {
		return nil
	}
	return err
}

// 删除
func (s SalesStatement) DelNotice(merchant_id string, id int) (err error) {

	rowsAffected := mysql.NewDB().Model(&models.MaSalesStatement{}).Where("id = ?", id).
		Delete(&models.MaSalesStatement{}).RowsAffected

	if rowsAffected > 0 {
		return nil
	}
	return err
}

// [安卓] 获取重要提示列表
func (s SalesStatement) ListNotice(ctx context.Context, merchant_id string, page, limit int) (
	result []models.MaSalesStatement, count int64, err error) {

	tx := mysql.NewDB().Model(&models.MaSalesStatement{})
	tx.Count(&count)
	result = []models.MaSalesStatement{}
	if page == 0 && limit == 0 {
		tx.Order("sort asc").Find(&result)
	} else {
		helper.Gorm{}.Paginate(tx, page, limit).Order("sort asc").Find(&result)
	}
	// 把create_at
	return
}

// 提示详情
func (s SalesStatement) DetailNotice(ctx context.Context, merchant_id string, id int) (
	result models.MaSalesStatement, err error) {

	tx := mysql.NewDB().Model(&models.MaSalesStatement{})
	tx.Where("id = ?", id).Take(&result)
	return
}

// 提示详情
func (s SalesStatement) SortNotice(ctx context.Context, merchant_id string, id, sort int) (err error) {
	var data models.MaSalesStatement
	data.Sort = sort
	rowsAffected := mysql.NewDB().Model(&models.MaSalesStatement{}).Where("id = ?", id).
		Updates(&data).RowsAffected
	// 写入数据
	if rowsAffected > 0 {
		return nil
	}
	return err
}
